﻿using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Linq;
using System.Threading;
using System.Web.Security;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Input;
using CCS;
using Microsoft.Samples.ServiceHosting.StorageClient;

namespace CCSAdmin
{
    /// <summary>
    /// Interaction logic for Home.xaml
    /// </summary>
    public partial class Home : Window
    {
        private List<CCSProduct> products = new List<CCSProduct>();

        public Home()
        {
            InitializeComponent();
        }

        void DeleteUser_CommandCompleted(object sender, CommandCompleteEventArgs e)
        {
            _UpdateUsersGrid();
        }

        private void AdminTabs_SelectionChanged(object sender, SelectionChangedEventArgs e)
        {
            if (e.Source is TabControl == false || App.Credentials == null)
            {
                return;
            }

            if (((TabItem)((TabControl)e.Source).SelectedItem).Name == showUsersTab.Name)
            {
                _UpdateUsersGrid();
            }

            if (((TabItem)((TabControl)e.Source).SelectedItem).Name == showAppsTab.Name)
            {
                _UpdateProductsGrid();
            }
        }

        private void _UpdateProductsGrid()
        {
            TableStorage tableStorage = StorageClientHelper.GetTableStorage();
            StorageAccountInfo accountInfo = StorageClientHelper.GetAccountInfo();
            products = Procedures.GetAllProducts(accountInfo).ToList();
            productDataGrid.ItemsSource = products;
        }

        private void _UpdateUsersGrid()
        {
            int total;
            CCS.CCS webService = new CCSAdmin.CCS.CCS();
            userDataGrid.ItemsSource = webService.GetAllUsers(App.Credentials);
        }

        private void LoginControl_LoggedIn(object sender, System.EventArgs e)
        {
            CCS.CCS webService = new CCSAdmin.CCS.CCS();
            if (webService.ValidateUser(App.Credentials))
            {
                DeleteUser.CommandCompleted += new EventHandler<CommandCompleteEventArgs>(DeleteUser_CommandCompleted);
                _UpdateUsersGrid();
                _UpdateProductsGrid();
                LoginControl.Visibility = Visibility.Hidden;
                AdminTabs.Visibility = Visibility.Visible;
            }
        }
    }
}